package svc

import (
	"github.com/zeromicro/go-zero/rest"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"trusteva/app/rbac/internal/config"
	"trusteva/app/rbac/internal/middleware"
	"trusteva/app/rbac/model"
)

type ServiceContext struct {
	Config          config.Config
	JwtAuth         rest.Middleware
	JwtWithRBACAuth rest.Middleware
	JwtMid          *middleware.JwtAuthMiddleware
	DB              *gorm.DB
}

func NewServiceContext(c config.Config) *ServiceContext {
	db, err := gorm.Open(mysql.Open(c.DB.DataSource), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
			NoLowerCase:   true,
		},
		DisableForeignKeyConstraintWhenMigrating: true,
		Logger:                                   logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic(err)
	}

	// 自动同步表结构
	if !c.Release {
		sync(db)
		//initRBAC(db)
	}

	jwtWithRBACMid := middleware.NewJwtWithRBACAuthMiddleware(db, c.JwtAuth.AccessSecret, c.JwtAuth.AccessExpire)
	jwtMid := middleware.NewJwtAuthMiddleware(db, c.JwtAuth.AccessSecret, c.JwtAuth.AccessExpire)

	return &ServiceContext{
		Config:          c,
		JwtAuth:         jwtMid.Handle,
		JwtWithRBACAuth: jwtWithRBACMid.Handle,
		JwtMid:          jwtMid,
		DB:              db,
	}
}

func sync(db *gorm.DB) {
	db.AutoMigrate(&model.ActionConfig{})
	db.AutoMigrate(&model.MenuConfig{})
	db.AutoMigrate(&model.RoleConfig{})
	db.AutoMigrate(&model.RoleMenuAction{})
	db.AutoMigrate(&model.User{})
	db.AutoMigrate(&model.UserLog{})
}
